package cn.com.libertymutual.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
/**
 * 获取spring context 的properties文件内容
 * @author xrxianga
 * @date 2014-6-17
 */
public class SpringContextUtil implements ApplicationContextAware {
	
	private static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);
	
	private static ApplicationContext applicationContext;
    private static Properties props = new Properties();
    private static InputStream in = null;
    static {
        try {
            in = SpringContextUtil.class.getResourceAsStream("/config/var.properties");
            props.load(in);
        } catch (IOException e) {
        	logger.error(e.getMessage(),e);
        }finally{
        	if(null!=in){
        		try {
					in.close();
				} catch (IOException e) {
					logger.error(e.getMessage(),e);
				}
        	}
        }
    }
    @Bean(name = {"config"})
    public Properties globalProperties() {
        return props;
    }
    
    public void setApplicationContext(ApplicationContext context) throws BeansException {
    	SpringContextUtil.applicationContext = context;
    }
    
    public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }  
    
    public static Properties getProperties() {
        if(props == null){
            props = (Properties)applicationContext.getBean("config");
        }
        return props;
    }
    
    public static String getProperty(String name) {
        return getProperties().getProperty(name);
    }

    public static String getProperty(String name,String defaultValue) {
        return getProperties().getProperty(name,defaultValue);
    }
}
